package com.geoway.adf.report.jpa;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Arrays;
import java.util.Optional;

/**
 * @Author: lzw
 * @Date: 2024/1/12 16:05
 * @Description: 注入审计用户名
 */
@Configuration
public class UserAuditorAware implements AuditorAware<String> {

    @Override
    public Optional<String> getCurrentAuditor() {
        String username = "";
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Cookie[] cookies = request.getCookies();
        if(null !=cookies && cookies.length>0){
            username = Arrays.stream(cookies).filter(e->e.getName().equals("username")).findAny().orElse(new Cookie("username","")).getValue();
        }
        if(StringUtils.hasText(username)){
            username = request.getHeader("username");
        }
        if(StringUtils.hasText(username)){
            username = request.getParameter("username");
        }
        if(StringUtils.hasText(username)){
            Principal userPrincipal = request.getUserPrincipal();
            username = userPrincipal.getName();
        }
        if(StringUtils.hasText(username)){
            username = (String)request.getAttribute("username");
        }
        return StringUtils.hasText(username)?Optional.of(username):Optional.of("sysadmin");
    }

}